package com.google.project.client.Director;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.MessageService;
import com.google.project.client.Service.MessageServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.TaskRequireService;
import com.google.project.client.Service.TaskRequireServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.client.Sharing.TaskReqDialog;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.MessageDTO;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectTaskDTO;
import com.google.project.shared.UsersDTO;

public class DRTHumanReqDetail extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true)
	CellTable<ProjectTaskDTO> ctbProjectTask = new CellTable<ProjectTaskDTO>();
	@UiField
	SimplePager pager;
	@UiField
	Label lblProjectName;
	@UiField
	Label lblNumOfEmp;
	@UiField
	Button btnBack;
	@UiField
	Button btnAccept;
	@UiField
	Label lblProjectDate;
	@UiField
	TextBox txtNumOfOPT;
	@UiField Button btnClear;
	@UiField
	TextArea taReponse;
	@UiField
	VerticalPanel pWidget;
	interface Binder extends UiBinder<Widget, DRTHumanReqDetail> {
	}

	private final TaskRequireServiceAsync taskReqSv = GWT
			.create(TaskRequireService.class);
	private final ProjectServiceAsync projectSv = GWT
			.create(ProjectService.class);
	private final MessageServiceAsync messService = GWT
	.create(MessageService.class);
	private final LoginServiceAsync loginService = GWT
	.create(LoginService.class);
	private final UsersServiceAsync userSv = GWT
	.create(UsersService.class);
	
	ProjectTaskDTO taskDTO = new ProjectTaskDTO();
	ProjectDTO currProject = new ProjectDTO();
	UsersDTO currentUserDTO = new UsersDTO();
	MessageDTO messDTO = new MessageDTO();
	List<MessageDTO> listMessage = new ArrayList<MessageDTO>();
	
	public DRTHumanReqDetail() {
		initWidget(binder.createAndBindUi(this));
	}

	// contructor
	public DRTHumanReqDetail(ProjectDTO projectDTO) {
		this.currProject = projectDTO;

		initWidget(binder.createAndBindUi(this));

		lblProjectDate.setText("("
				+ CommonFuntion.convertToDate(new Date(currProject
						.getStartDate()))
				+ " - "
				+ CommonFuntion
						.convertToDate(new Date(currProject.getDueDate()))
				+ ")");
		lblProjectName.setText("Dự án: " + currProject.getProjectName());
		lblNumOfEmp.setText(currProject.getNumOfEmpReq() + " (Nhân viên)");
		txtNumOfOPT.setText(currProject.getNumOfOPT()+"");
		initTable();
		bindData(currProject.getProjectID());
		getMessByProject();

		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	txtNumOfOPT.setFocus(true);
	        }
	    });
		// get info user from session + lấy thông tin giám đốc with userCode=mg4
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(UsersDTO result) {
				currentUserDTO = result;
				// get name, id cua PM
				userSv.getInfoByUserCode("mg4",
						new AsyncCallback<List<UsersDTO>>() {

							@Override
							public void onFailure(Throwable caught) {
							}

							@Override
							public void onSuccess(List<UsersDTO> result) {
								// pm phan hoi toi dr
								if (currentUserDTO.getUserGroup()==2) {
									messDTO.setSenderId(currentUserDTO
											.getUserId());
									messDTO.setSenderName(currentUserDTO
											.getUserName());
									messDTO.setReceiverId(result.get(0).getUserId());
									messDTO.setReceiverName(result
											.get(0).getUserName());
								} else if(currentUserDTO.getUserGroup()==1) { // dr gui lai pm
									messDTO.setSenderId(result.get(0).getUserId());
									messDTO.setSenderName(result
											.get(0).getUserName());
									messDTO.setReceiverId(currentUserDTO
											.getUserId());
									messDTO.setReceiverName(currentUserDTO
											.getUserName());
								}
							}
						});

			}

		});
	}

	/***
	 * lấy về tất cả task con ko cha theo projectId
	 */
	public void bindData(String projectId) {
		try {
			taskReqSv.getListTask(projectId,
					new AsyncCallback<List<ProjectTaskDTO>>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onSuccess(List<ProjectTaskDTO> result) {
							loadData(result);

						}
					});
		} catch (Exception ex) {
			ex.getMessage();
		}

	}

	// Ham tao Cell table
	public void initTable() {
		// STT
		TextColumn<ProjectTaskDTO> indexColumn = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return object.getSTT();
			}
		};

		TextColumn<ProjectTaskDTO> taskNameColumn = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return object.getTaskName();
			}
		};
		// số nhân viên yêu cầu
		Column<ProjectTaskDTO, String> numOfEmpColumn = new Column<ProjectTaskDTO, String>(
				new ClickableTextCell()) {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return object.getNumOfEmp() + " (Nhân viên)";
			}
		};
		numOfEmpColumn
				.setFieldUpdater(new FieldUpdater<ProjectTaskDTO, String>() {
					@Override
					public void update(int index,
							ProjectTaskDTO projectTaskDTO, String value) {
						// chuyển sang TaskReqDialog
						TaskReqDialog dialog = new TaskReqDialog(
								projectTaskDTO, currProject);
						dialog.setPopupPosition(345, 100);
						dialog.show();
					}
				});

		TextColumn<ProjectTaskDTO> startDateColumn = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return CommonFuntion.convertToDate(new Date(object
						.getStartDate()));
			}
		};
		TextColumn<ProjectTaskDTO> dueDateColumn = new TextColumn<ProjectTaskDTO>() {
			@Override
			public String getValue(ProjectTaskDTO object) {
				return CommonFuntion
						.convertToDate(new Date(object.getDueDate()));
			}
		};

		ctbProjectTask.setWidth("100%", true);
		ctbProjectTask.setPageSize(5);
		ctbProjectTask.setPageStart(0);
		ctbProjectTask.setStyleName("ttable");

		ctbProjectTask.addColumn(indexColumn, "STT");
		ctbProjectTask.setColumnWidth(indexColumn, 30.0, Unit.PX);

		ctbProjectTask.addColumn(taskNameColumn, "Tên công việc");

		ctbProjectTask.setColumnWidth(taskNameColumn, 40.0, Unit.PCT);
		taskNameColumn.setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		ctbProjectTask.addColumn(numOfEmpColumn, "Số lượng");
		ctbProjectTask.setColumnWidth(numOfEmpColumn, 140.0, Unit.PX);
		numOfEmpColumn.setCellStyleNames("celltable");
		ctbProjectTask.getColumn(ctbProjectTask.getColumnIndex(numOfEmpColumn))
				.setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		ctbProjectTask.addColumn(startDateColumn, "Từ ngày");
		ctbProjectTask.setColumnWidth(startDateColumn, 20.0, Unit.PCT);
		ctbProjectTask
				.getColumn(ctbProjectTask.getColumnIndex(startDateColumn))
				.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

		ctbProjectTask.addColumn(dueDateColumn, "Đến ngày");
		ctbProjectTask.setColumnWidth(dueDateColumn, 20.0, Unit.PCT);
		ctbProjectTask.getColumn(ctbProjectTask.getColumnIndex(dueDateColumn))
				.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);

	}

	public void loadData(List<ProjectTaskDTO> projectTaskList) {
		// Create a data provider.
		ListDataProvider<ProjectTaskDTO> dataProvider = new ListDataProvider<ProjectTaskDTO>();

		int index = 1;
		List<ProjectTaskDTO> list = dataProvider.getList();
		for (ProjectTaskDTO projectTaskDTO : projectTaskList) {
			projectTaskDTO.setSTT(index + "");
			list.add(projectTaskDTO);
			index++;

		}
		pager.setDisplay(ctbProjectTask);
		dataProvider.addDataDisplay(ctbProjectTask);
	}

	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		DRTEntrypoint.get().DRTHumanReq();
	}

	@UiHandler("btnAccept")
	void onBtnAcceptClick(ClickEvent event) {
		try {
			if(currProject.getIsReq()==1){
				if (Window.confirm("Duyệt yêu cầu nhân sự này?")) {
					currProject.setIsReq(2);
					projectSv.updateProject(currProject, new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onSuccess(Void result) {
							Window.alert("Yêu cầu nhân sự được xác nhận!");
							DRTEntrypoint.get().DRTHumanReq();
						}
					});
				}
			}else if(currProject.getIsReq()==2 || currProject.getIsReq()==3 || currProject.getIsReq()==4){
				Window.alert("Yêu cầu nhân sự này đã được duyệt!");
			}
			
		} catch (Exception ex) {
		}
	}
	@UiHandler("btnClear")
	void onBtnClearClick(ClickEvent event) {
		try {
			if(currProject.getIsReq()==1){
				if (Window.confirm("Không chấp nhận yêu cầu nhân sự này?")) {
					currProject.setIsReq(0);
					currProject.setNumOfOPT(0);
					projectSv.updateProject(currProject, new AsyncCallback<Void>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onSuccess(Void result) {
							Window.alert("Hủy thành công!");
						}
					});
				}
			}else if(currProject.getIsReq()==2 || currProject.getIsReq()==3 || currProject.getIsReq()==4){
				Window.alert("Yêu cầu này đã được duyêt!");
			}
			
		} catch (Exception ex) {
		}
	}
	// get all Message có TypeID=6
	public void getMessByProject() {
		messService.getMessageList(new AsyncCallback<List<MessageDTO>>() {

			@Override
			public void onSuccess(List<MessageDTO> result) {
				try {
//					for (MessageDTO messageDTO : result) {
//						listMessage.add(messageDTO);
//					}

					List<MessageDTO> tempMess = new ArrayList<MessageDTO>();
					for (MessageDTO mess : result) {
						if (mess.getProjectId()!=null && mess.getTypeId()==6 && mess.getProjectId().equals(currProject.getProjectID())) {
							tempMess.add(mess);
						}
					}
					String top = "<div class=\"container3\"><div class=\"smallpbox\"><div class=\"smallpboxtl\"></div><div class=\"smallpboxtr\"></div></div><div class=\"smallpboxcnt\">";
					String bottom = "</div><div class=\"smallpboxbtm\"><div class=\"smallpboxbtml\"></div><div class=\"smallpboxbtmr\"></div></div></div>";
					String top2 = "<div class=\"container2\"><div class=\"smallpbox\"><div class=\"smallpboxtl\"></div><div class=\"smallpboxtr\"></div></div><div class=\"smallpboxcnt\">";
					String bottom2 = "</div><div class=\"smallpboxbtm\"><div class=\"smallpboxbtml\"></div><div class=\"smallpboxbtmr\"></div></div></div>";
					if (tempMess != null && tempMess.size() > 0) {
						int r = tempMess.size();
						int c = 1;
						Grid grid = new Grid(r, c);
						pWidget.add(grid);
						for (int i = 0; i < tempMess.size(); i++) {
							String senderName = tempMess.get(i).getSenderName();
							String content = tempMess.get(i).getContent();
							String createdOnDate = CommonFuntion
									.convertToDate(new Date(tempMess.get(i)
											.getCreatedOnDate()));
							grid.setWidget(i, 0, new HTML(top + "Người Gửi: "
									+ senderName + " <br> Ngày Gửi: "
									+ createdOnDate + "<br><br>" + top2
									+ content + bottom2 + bottom + "<br>"));
						}

					}


				} catch (Exception ex) {
					ex.getMessage();
				}
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}

	@UiHandler("btnReponse")
	void onBtnReponseClick(ClickEvent event) {
		if (taReponse.getText() != null
				&& !taReponse.getText().equalsIgnoreCase("")) {
			messDTO.setContent(taReponse.getText());
			messDTO.setCreatedOnDate(new Date().getTime());
			messDTO.setProjectId(currProject.getProjectID());
			messDTO.setTypeId(6);
			messService.sendMessage(messDTO, new AsyncCallback<MessageDTO>() {
				@Override
				public void onFailure(Throwable caught) {
				}
				@Override
				public void onSuccess(MessageDTO result) {
					pWidget.clear();
					//listMessage.clear();
					getMessByProject();
					taReponse.setText("");
					Window.alert("Gửi phản hồi thành công!");

					Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
				        public void execute () {
				        	taReponse.setFocus(true);
				        }
				    });
				}
			});
		}else{
			Window.alert("Bạn chưa nhập nội dung phản hồi");
		}
	
	}
}
